package ir;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: Apr 22, 2010
 * Time: 1:28:26 PM
 * To change this template use File | Settings | File Templates.
 */
public class Sourse {

    static void parseXML(String path) throws Exception {
        File file = new File(path);
        if (file.length() == 0) {
            throw new IllegalArgumentException("file size is zero");
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        doc.getDocumentElement().normalize();
        NodeList nodeLst = doc.getElementsByTagName("PubmedArticle");
        Collection<IArticle> list = new ArrayList<IArticle>();
        for (int s = 0; s < nodeLst.getLength(); s++) {
            Node fstNode = nodeLst.item(s);

            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                Element fstElmnt = (Element) fstNode;
                NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("PMID");
                Node fstNmElmnt = fstNmElmntLst.item(0);
                NodeList fstNm = fstNmElmnt.getChildNodes();

                NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("ArticleTitle");
                Node lstNmElmnt = lstNmElmntLst.item(0);
                NodeList lstNm = lstNmElmnt.getChildNodes();

                NodeList srcNmElmntLst = fstElmnt.getElementsByTagName("AbstractText");
                Node srcNmElmnt = srcNmElmntLst.item(0);
                NodeList srcNm = srcNmElmnt.getChildNodes();

                list.add(getArticle(fstNm.item(0).getNodeValue(), lstNm.item(0).getNodeValue(), srcNm.item(0).getNodeValue()));
            }

        }
        checkSentence(list);
    }
    private static void addValue(IArticle a) {
        a.setDel(23);
    }

    private static IArticle getArticle(String id, String title, String article) {
        IArticle al = new Article();
        al.setPmid(id);
        al.setArticleTile(title);
        al.setArticleSource(article);
        addValue(al);
        return al;

    }

    static void checkSentence(Iterable<IArticle> list) {
        for (IArticle res : list) {
            for (String key : Phases.APPROVED_PHASES) {
                if (res.getArticleSource().contains(key)) {
//                    System.out.println("res: " + res.getArticleTile());
//                    System.out.println("res: " + res.getDel());
                }
            }
        }
    }


    public static void main(String[] args) throws Exception {
        parseXML("E:\\temp\\pubmed_result.xml");
    }
}
